package com.bm.connect.websocket;

import com.bm.connect.service.ChatService;
import com.bm.connect.vo.MessageDTO;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Objects;

public  class SimpleChatHandler extends TextWebSocketHandler {
    private final ChatService chatService;

    public SimpleChatHandler(ChatService chatService) {
        this.chatService = chatService;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        // 从URL参数中获取用户名
        String username= Objects.requireNonNull(session.getUri()).getQuery().split("=")[1];
//        System.out.println(username);
//        = uriVariables.get("user");
        chatService.addSession(session, username);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        chatService.removeSession(session); // 连接关闭时移除
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 解析 JSON 消息
        MessageDTO messageDTO = MessageDTO.parse(message.getPayload());
        String senderUsername = chatService.getUsername(session.getId());
        messageDTO.setSender(senderUsername);


        if (messageDTO.getIsPrivate()) {
            // 私聊消息
            chatService.sendPrivateMessage(session, messageDTO.getReceiver(), messageDTO.getMessage());
        } else {
            // 广播消息
            chatService.broadcastMessage(session, messageDTO.toJson());
        }
    }

}
